package com.filetransfer.view.Panel;
import com.filetransfer.api.ApiHelper;
import com.filetransfer.api.generated.StatisticControllerApi;
import com.filetransfer.api.generated.invoker.ApiException;
import com.filetransfer.api.generated.models.FileCategoryModel;
import com.filetransfer.api.generated.models.ServerInfo;
import com.filetransfer.api.generated.models.ServiceInfo;
import com.filetransfer.api.generated.models.ServiceInfo5Day;
import com.filetransfer.utils.RetryExecutor;
import com.filetransfer.view.Components.StatisticsDataPanel;
import com.filetransfer.view.Components.TaskChartPanel;
import lombok.extern.slf4j.Slf4j;
import raven.chart.data.pie.DefaultPieDataset;

import javax.swing.*;
import java.awt.*;
import java.util.List;
@Slf4j
public class StatisticsPanel extends JPanel {
    private final StatisticsDataPanel statisticsDataPanel;
    private final TaskChartPanel taskChartPanel;
    public StatisticsPanel() {
        setLayout(new BorderLayout());
        // 统计信息面板（左侧）
        statisticsDataPanel = new StatisticsDataPanel();
        add(statisticsDataPanel, BorderLayout.WEST);
        // 任务图表面板（右侧）
        taskChartPanel = new TaskChartPanel();
        add(taskChartPanel, BorderLayout.CENTER);
        // 启动数据获取与更新线程
        new Thread(() -> fetchDataAndUpdateUI()).start();
    }
    private void fetchDataAndUpdateUI() {
        RetryExecutor<Void> retryExecutor = new RetryExecutor<>(3, 2000, 2); // 最大重试3次，间隔2秒
        retryExecutor.submit(() -> {
            StatisticControllerApi api = new StatisticControllerApi(
                    ApiHelper.newApiClient()
            );
            ServerInfo serverInfo = null;
            ServiceInfo serviceInfo = null;
            List<FileCategoryModel> fileCategoryInfo = null;
            ServiceInfo5Day serviceInfo5Day = null;
            try {
                // 获取数据
                serverInfo = api.getServerInfo();
                serviceInfo = api.getServiceInfo();
                fileCategoryInfo = api.getFileCategoryInfo();
                serviceInfo5Day = api.getServiceInfo5Day();
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
            // 将数据传递给 UI 进行更新
            ServerInfo finalServerInfo = serverInfo;
            ServiceInfo finalServiceInfo = serviceInfo;
            List<FileCategoryModel> finalFileCategoryInfo = fileCategoryInfo;
            ServiceInfo5Day finalServiceInfo5Day = serviceInfo5Day;
            SwingUtilities.invokeLater(() -> {
                updateUIWithData(finalServerInfo, finalServiceInfo, finalFileCategoryInfo, finalServiceInfo5Day);
            });
            return null;
        }, result -> {
            if (result.isSuccess()) {
                log.info("Statistics data updated successfully.");
            } else {
                log.error("Error fetching data from API after retries.");
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread(retryExecutor::shutdown));
    }
    private void updateUIWithData(ServerInfo serverInfo, ServiceInfo serviceInfo, List<FileCategoryModel> fileCategoryInfo, ServiceInfo5Day serviceInfo5Day) {
        // 更新左侧统计信息面板
        statisticsDataPanel.updateStatistics(
                String.valueOf(serviceInfo.getFileInfo().getFileCount()),
                String.valueOf(serviceInfo.getFileInfo().getTotalSize()),
                String.valueOf(serviceInfo.getFileInfo().getTotalDownloadCount()),
                String.valueOf(serviceInfo.getFileInfo().getTotalDownloadSize())
        );
        // 更新右侧任务图表
        DefaultPieDataset<String> pieDataset = new DefaultPieDataset<>();
        for (FileCategoryModel category : fileCategoryInfo) {
            pieDataset.addValue(category.getFileType().getValue(), category.getFileCount());
        }
        taskChartPanel.updateLineChartData(serviceInfo5Day);
        taskChartPanel.updateBarChartData(pieDataset);
    }
}

